<template>
  <el-dialog
    :model-value="visible"
    :title="isEdit ? '编辑成绩' : '录入成绩'"
    width="600px"
    :before-close="handleClose"
    @closed="handleClosed"
  >
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      label-position="right"
    >
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="学生" prop="studentId">
            <el-select
              v-model="formData.studentId"
              placeholder="请选择学生"
              filterable
              clearable
              style="width: 100%"
              :disabled="isEdit"
            >
              <el-option
                v-for="student in studentList"
                :key="student.id"
                :label="`${student.name} (${student.sno})`"
                :value="student.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="课程" prop="courseId">
            <el-select
              v-model="formData.courseId"
              placeholder="请选择课程"
              filterable
              clearable
              style="width: 100%"
              :disabled="isEdit"
            >
              <el-option
                v-for="course in courseList"
                :key="course.id"
                :label="`${course.name} (${course.code})`"
                :value="course.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-row :gutter="20">
        <el-col :span="12">
          <el-form-item label="成绩" prop="score">
            <el-input-number
              v-model="formData.score"
              :min="0"
              :max="100"
              :precision="2"
              placeholder="请输入成绩"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="考试日期" prop="examDate">
            <el-date-picker
              v-model="formData.examDate"
              type="date"
              placeholder="请选择考试日期"
              style="width: 100%"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-form-item>
        </el-col>
      </el-row>
      
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="formData.remark"
          type="textarea"
          :rows="3"
          placeholder="请输入备注信息（可选）"
          maxlength="200"
          show-word-limit
        />
      </el-form-item>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" :loading="loading" @click="handleSubmit">
          {{ isEdit ? '更新' : '录入' }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, reactive, computed, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import { createScoreApi, updateScoreApi } from '@/api/score/score'

// Props
const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  scoreData: {
    type: Object,
    default: () => ({})
  },
  studentList: {
    type: Array,
    default: () => []
  },
  courseList: {
    type: Array,
    default: () => []
  }
})

// Emits
const emit = defineEmits(['update:visible', 'success'])

// Refs
const formRef = ref()
const loading = ref(false)

// 计算属性
const isEdit = computed(() => {
  return props.scoreData && props.scoreData.id
})

// 表单数据
const formData = reactive({
  id: null,
  studentId: null,
  courseId: null,
  score: null,
  examDate: '',
  remark: ''
})

// 表单验证规则
const formRules = {
  studentId: [
    { required: true, message: '请选择学生', trigger: 'change' }
  ],
  courseId: [
    { required: true, message: '请选择课程', trigger: 'change' }
  ],
  score: [
    { required: true, message: '请输入成绩', trigger: 'blur' },
    { type: 'number', min: 0, max: 100, message: '成绩必须在0-100之间', trigger: 'blur' }
  ],
  examDate: [
    { required: true, message: '请选择考试日期', trigger: 'change' }
  ]
}

// 监听scoreData变化，初始化表单数据
watch(() => props.scoreData, (newData) => {
  if (newData && Object.keys(newData).length > 0) {
    Object.assign(formData, {
      id: newData.id || null,
      studentId: newData.studentId || null,
      courseId: newData.courseId || null,
      score: newData.score || null,
      examDate: newData.examDate || '',
      remark: newData.remark || ''
    })
  }
}, { immediate: true, deep: true })

// 监听对话框显示状态
watch(() => props.visible, (visible) => {
  if (visible) {
    nextTick(() => {
      formRef.value?.clearValidate()
    })
  }
})

// 方法
const handleClose = () => {
  emit('update:visible', false)
}

const handleClosed = () => {
  // 重置表单数据
  Object.assign(formData, {
    id: null,
    studentId: null,
    courseId: null,
    score: null,
    examDate: '',
    remark: ''
  })
  formRef.value?.resetFields()
}

const handleSubmit = async () => {
  try {
    // 表单验证
    await formRef.value.validate()
    
    loading.value = true
    
    const submitData = {
      studentId: formData.studentId,
      courseId: formData.courseId,
      score: formData.score,
      examDate: formData.examDate,
      remark: formData.remark
    }
    
    if (isEdit.value) {
      // 编辑模式
      submitData.id = formData.id
      await updateScoreApi(submitData)
      ElMessage.success('成绩更新成功')
    } else {
      // 新增模式
      await createScoreApi(submitData)
      ElMessage.success('成绩录入成功')
    }
    
    emit('success')
    handleClose()
    
  } catch (error) {
    console.error('提交失败:', error)
    if (error.response?.data?.message) {
      ElMessage.error(error.response.data.message)
    } else {
      ElMessage.error(isEdit.value ? '成绩更新失败' : '成绩录入失败')
    }
  } finally {
    loading.value = false
  }
}
</script>

<style lang="scss" scoped>
.dialog-footer {
  text-align: right;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-input-number) {
  width: 100%;
}
</style>
